<script setup lang="ts">
import { ref, unref, onMounted, watch, onBeforeUnmount, nextTick } from 'vue'
import { propTypes } from '@/utils/propTypes'
import Player from 'xgplayer'
import Mp4Plugin from 'xgplayer-mp4'
import 'xgplayer/dist/index.min.css'

// See https://h5player.bytedance.com/config/
const props = defineProps({
  title: propTypes.string.def(''),
  url: propTypes.string.def(''),
  poster: propTypes.string.def(''),
  controls: propTypes.bool.def(true),
  autoplay: propTypes.bool.def(false),
  muted: propTypes.bool.def(false),
  isLive: propTypes.bool.def(false),
  loop: propTypes.bool.def(false),
  preload: propTypes.string.def('none'),
  width: propTypes.number.def(140),
  height: propTypes.number.def(140)
})

const playerRef = ref<Player>()

const videoEl = ref<HTMLDivElement>()

const intiPlayer = () => {
  if (!unref(videoEl)) return
  playerRef.value = new Player({
    ...props,
    autoplayMuted: props.muted,
    // See https://h5player.bytedance.com/plugins/extension/xgplayer-mp4.html
    plugins: [Mp4Plugin],
    mp4plugin: {
      maxBufferLength: 30,
      minBufferLength: 10,
      reqOptions: {
        mode: 'cors',
        method: 'GET',
        headers: {
          // 需要带的自定义请求头
          'X-Player': 'xgplayer'
        }
      }
    },
    el: unref(videoEl)
  })
}

onMounted(() => {
  intiPlayer()
})

watch(
  () => props,
  async (newProps) => {
    await nextTick()
    if (newProps) {
      unref(playerRef)?.setConfig(newProps)
    }
  },
  {
    deep: true
  }
)

onBeforeUnmount(() => {
  unref(playerRef)?.destroy()
})

defineExpose({
  playerExpose: () => unref(playerRef)
})
</script>

<template>
  <div class="flex flex-col items-center justify-center">
    <div ref="videoEl"></div>
    <el-text v-if="props.title">{{ props.title }}</el-text>
  </div>
</template>
